<?php
/**
 * Created by PhpStorm.
 * User: 671643387
 * Date: 2016/9/8
 * Time: 10:14
 */

function json_encode_ex($value)
{
    if (version_compare(PHP_VERSION,'5.4.0','<')) {
        $str = json_encode($value);
        $str = preg_replace_callback(
            "#\\\u([0-9a-f]{4})#i",
            function($matchs)
            {
                return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
            },
            $str
        );
        return $str;
    }
    else {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 格式化邮件字符串
 * @param $receiver     收件人
 * @param $subject      标题
 * @param $body         内容
 * @param $money        金币
 * @param $item_id      道具编号
 * @param $item_count   道具数量
 * @return string
 */
function format_mail($receiver, $subject, $body, $money, $item_id, $item_count) {
    $mailData = array(
        'receiver'      => $receiver,
        'subject'       => $subject,
        'body'          => $body,
        'money'         => $money,
    );
    if ($item_id != 0) {
        $mailData['items'] = array(
            array( 'id' => $item_id, 'count' => $item_count )
        );
    }
    return json_encode_ex($mailData);
}

/**
 * 获取数据库连接串
 * @param $dbname
 * @return string
 */
function getDBString($dbname) {
    return sprintf('mysql://%s:%s@%s:%d/%s',
        C('DB_USER'),
        C('DB_PWD'),
        C('DB_HOST'),
        C('DB_PORT'),
        $dbname
    );
}

/**
 * 获取登录数据库连接串
 * @return string
 */
function getRealmdDBString() {
    return getDBString(C('REALMD_DB'));
}

/**
 * 获取角色数据库连接串
 * @return string
 */
function getCharaDBString() {
    return getDBString(C('CHARA_DB'));
}

/**
 * 获取游戏数据库连接串
 * @return string
 */
function getMangosDBString() {
    return getDBString(C('MANGOS_DB'));
}

/**
 * 检查角色是否存在
 * @param $name
 * @return bool
 */
function characterExists($name) {
    $model = M('', '', getCharaDBString());
    $res = $model->query(sprintf("SELECT guid FROM characters WHERE name='%s';"), $name);
    return count($res) > 0;
}

/**
 * 生成订单号
 * @param $charaname
 * @param $money
 * @return string
 */
function genOrderId($charaname, $money) {
    return date('Y-m-d H:i:s',time()) . 'T' . $charaname . 'T' . $money;
}

/**
 * @param $orderId
 * @param $charaname
 * @param $money
 * @return bool创建订单
 */
function createOrder($orderId, $charaname, $money) {
    $model = M('', '', getMangosDBString());
    return !($model->execute(sprintf("INSERT INTO order VALUE (0, '%s', '%s', %d, 0, CURRENT_TIMESTAMP);"),
            $orderId, $charaname, $money) == false
    );
}

/**
 * 更新订单状态
 * @param $orderId
 * @param $state
 * @return bool
 */
function updateOrder($orderId, $state) {
    $model = M('', '', getMangosDBString());
    return !($model->execute(sprintf("UPDATE order SET state=%d where orderid='%s';", $state, $orderId)) == false);
}

/**
 * 给玩家发金币邮件
 * @param $charaname
 * @param $gold
 */
function sendGoldMail($charaname, $gold) {
    // 查询角色GUID
    $model = M('', '', getCharaDBString());
    $res = $model->query(sprintf("SELECT guid FROM characters WHERE name='%s';"), $name);
    $charaGuid = intval($res[0]['guid']);

    // 生成邮件字符串
    $mailStr = format_mail($charaGuid, 'GM-金币购买', '请查收您购买的' , $gold . '金币', $gold, 0, 0);

    // 发送邮件
    $model = M('', '', getMangosDBString());
    if ($model->execute("INSERT INTO gm_cmds values (0, $cmd_id, '$mailStr', 0, CURRENT_TIMESTAMP);") == false) {
        return false;
    }
    return true;
}